from django.conf import settings
from django.utils.translation import ugettext as _
from django.template.loader import render_to_string
from django.contrib.gis.geos import Point
from django.contrib.auth.models import User
from django.core.cache import cache
from django.utils import simplejson

from mobile.models import Entry, CAPVIncident, CAPVIncidentCapture, CAPVPuertoCapture, CAPVPuertoIncident, Camera

def city_entries(request, city):
    out = []
    entries = Entry.objects.filter(city__id=city)
    for entry in entries:
        last_capture = entry.get_last_capture()
        cameras = [(camera.name,camera.url) for camera in entry.get_cameras()]
        data = {'id':entry.id, 'label':entry.label, 'status':last_capture.status,'status_display':last_capture.get_status_display(), 'date':last_capture.created.strftime("%d/%m/%y %H:%M"), 'cameras':cameras,'city_id':entry.city.id}
        out.append(data)
    return simplejson.dumps(out)

def incident_near_me(request, position, carretera):
    out = [[],[]]
    
    capture = CAPVIncidentCapture.get_last_capture()
    incidents = CAPVIncident.objects.filter(capture=capture).distance("POINT (%s)" % position).order_by('distance')
    for incident in incidents:
        if incident.distance.m < 15000:
            data = {'carretera':incident.carretera.name}
            data['lat'] = incident.point.x
            data['lng'] = incident.point.y
            data['km'] = incident.km
            data['sentido'] = incident.sentido
            data['afeccion'] = incident.afeccion
            data['retencion'] = incident.retencion
            data['municipio'] = incident.municipio.name
            data['causa'] = incident.get_razon()
            distance = incident.distance.m
            if distance >=1000:
                distance = '%.0fkm' % (distance/1000.0)
            else:
                distance = '%.0fm' % distance
            data['distance'] = distance
            out[0].append(data)
    
    if carretera:
        incidents = CAPVIncident.objects.filter(carretera__name=carretera.upper(),capture=capture).distance("POINT (%s)" % position).order_by('distance')
        for incident in incidents:
            data = {'carretera':incident.carretera.name}
            data['lat'] = incident.point.x
            data['lng'] = incident.point.y
            data['km'] = incident.km
            data['sentido'] = incident.sentido
            data['afeccion'] = incident.afeccion
            data['retencion'] = incident.retencion
            data['municipio'] = incident.municipio.name
            data['causa'] = incident.get_razon()
            distance = incident.distance.m
            if distance >=1000:
                distance = '%.0fkm' % (distance/1000.0)
            else:
                distance = '%.0fm' % distance
            data['distance'] = distance
            out[1].append(data)
    return simplejson.dumps(out)

def get_available_roads(request):
    def bylength(word1, word2):
        return len(word1) - len(word2)
    out = {}
    capture = CAPVIncidentCapture.get_last_capture()
    incidents = CAPVIncident.objects.filter(capture=capture)
    for incident in incidents:
        try:
            out[incident.carretera.name]+=1
        except:
            out[incident.carretera.name]=1
    
    out = out.keys()
    out.sort(cmp=bylength)
    return simplejson.dumps(out)

def incidents_in_road(request, road):
    capture = CAPVIncidentCapture.get_last_capture()
    incidents = CAPVIncident.objects.filter(capture=capture,carretera__name=unicode(road))
    out = []
    for incident in incidents:
        data = {}
        data['carretera'] = incident.carretera.name
        data['lat'] = incident.point.x
        data['lng'] = incident.point.y
        data['km'] = incident.km
        data['sentido'] = incident.sentido
        data['afeccion'] = incident.afeccion
        data['retencion'] = incident.retencion
        data['municipio'] = incident.municipio.name
        data['causa'] = incident.get_razon()
        data['distance'] = ""
        out.append(data)
    return simplejson.dumps(out)

def get_puertos(request):
    capture = CAPVPuertoCapture.get_last_capture()
    incidents = CAPVPuertoIncident.objects.filter(capture=capture).order_by("puerto__name")
    out = [[],[]]
    for incident in incidents:
        data = {}
        data['situacion'] = incident.situacion
        data['estado_turismos'] = incident.estado_turismos
        data['estado_articulados'] = incident.estado_articulados
        data['estado_camiones'] = incident.estado_camiones
        data['vialidad'] = incident.vialidad
        try:
            data['lat'] = incident.puerto.point.x
            data['lng'] = incident.puerto.point.y
        except:
            data['lat'] = ""
            data['lng'] = ""
        data['name'] = incident.puerto.name
        data['label'] = incident.puerto.label
        data['red'] = incident.puerto.red
        data['provincia'] = incident.puerto.provincia.name
        data['carretera'] = incident.puerto.carretera.name
        data['capture'] = incident.capture.datetime.strftime("%d/%m/%y %H:%M")
        if(data['red'] == "Prim."):
            out[0].append(data)
        else:
            out[1].append(data)
    return simplejson.dumps(out)

def get_near_cameras(request, position):
    out = []
    try:
        cameras = Camera.objects.all().distance("POINT (%s)" % position).order_by('distance')[:10]
    except:
        return simplejson.dumps(out)
        
    for camera in cameras:
        if camera.distance.m <= 15000:
            data = {}
            data['label'] = camera.label
            data['url'] = camera.url
            distance = camera.distance.m
            if distance >=1000:
                distance = '%.0fkm' % (distance/1000.0)
            else:
                distance = '%.0fm' % distance
            data['distance'] = distance
            out.append(data)
    return simplejson.dumps(out)